/**
 * Created by liushuai on 2017/8/22.
 */

var website = {
    category_id: null,
    title: null,
    urls: null,
    timerId: 0,
    content: null,
    page: 0,

    init: function () {
        website.category_id = $('[name=category_id]');
        website.title = $('[name=title]');
        website.content = $('#content');

        website.category_id.change(function () {
            website.page = 0;
            website.loadData();
        });
        website.title.keyup(function (e) {
            website.page = 0;
            if (e.keyCode == 13 || e.keyCode == 32) {

                website.loadData();
                return;
            }

            var title = website.title.val();

            if (website.timerId || title.length < 5) {
                clearTimeout(website.timerId);
                website.timerId = 0;
            }


            website.timerId = setTimeout(website.loadData, 600);
        });

        website.initBind();
        website.focus();
        website.initEvent();
        website.loadData();

    },

    initBind: function () {
        website.urls = $('.website_url');
    },

    initEvent: function () {
        $('.pagination a').click(function () {
            website.page = $(this).attr('data-page');
            website.loadData();
        });

        website.urls.click(function () {
            var id = $(this).attr('data-id');
            $.ajax({
                url: '/website/jump',
                type: 'post',
                dataType: 'json',
                data: {id: id},
                success: function () {
                    //website.loadData();
                    _hmt.push(['_trackEvent', 'website', 'jump', JSON.stringify(id)]);
                }
            });
        });

    },

    focus: function () {
        var title = website.title.val();
        website.title.val('');
        website.title.focus();
        website.title.val(title);
    },
    loadData: function () {

        var category_id = website.category_id.val();
        var title = website.title.val();
        var url = '/website/data';
        var page = website.page;
        var data_post = {category_id: category_id, title: title, page: page};
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            data: data_post,
            success: function (data) {
                website.content.html(data.data);
                $('.pagination a').attr('href', 'javascript:void(0)');
                website.initBind();
                website.initEvent();
                _hmt.push(['_trackEvent', 'website', 'loadData', JSON.stringify(data_post)]);
            }
        });
    }

};
$(function () {
    website.init();
});